const Router = require("koa-router");
const { Auth } = require("../../../middlewares/auth");
const { HotBook } = require("../../../models/hot-books");
const {
  PositiveIntegerValidator,
  SearchValidator,
  AddShortCommentValidator,
  CommentListValidator,
} = require("../../validator/validator");
const { Book } = require("../../../models/book");
const { Like } = require("../../../models/like");
const { Comments } = require("../../../models/book-comments");
const router = new Router({
  prefix: "/v1/book",
});

router.get("/:id/detail", new Auth().m, async (ctx, next) => {
  const v = await new PositiveIntegerValidator().validate(ctx);
  const data = await new Book().getDetail(v.get("path.id"));
  ctx.body = {
    data,
  };
});

router.get("/search", new Auth().m, async (ctx) => {
  const v = await new SearchValidator().validate(ctx);
  const data = await Book.getSearchList(
    v.get("query.q"),
    v.get("query.start"),
    v.get("query.count")
  );
  ctx.body = {
    data,
  };
});

router.get("/hot_list", new Auth().m, async (ctx, next) => {
  const data = await HotBook.getData();
  ctx.body = { data };
});

// 某个书籍的点赞情况
router.get("/:id/favor", new Auth().m, async (ctx) => {
  const v = await new PositiveIntegerValidator().validate(ctx);
  const data = await Like.getBookLike(ctx.auth.uId, v.get("path.id"));
  ctx.body = {
    data,
  };
});

// 点赞数量
router.get("/favor/count", new Auth().m, async (ctx) => {
  const like = await Like.count({
    where: {
      uid: ctx.auth.uId,
      type: 400,
    },
  });
  ctx.body = {
    data: like,
  };
});

router.post("/add/short_comment", new Auth().m, async (ctx) => {
  const v = await new AddShortCommentValidator().validate(ctx, {
    id: "book_id",
  });
  const data = await Comments.addComment(v.get("body.book_id"), v.get("body.content"));

  throw new global.errs.Success();
});

router.get("/getComment", new Auth().m, async (ctx) => {
  const v = await new CommentListValidator().validate(ctx, {
    id: "bookId",
  });
  const data = await Comments.getComment(
    v.get("query.bookId"),
    v.get("query.start"),
    v.get("query.count")
  );
  data.forEach(el => {
    el.exclude= ["nums"];
  });

  ctx.body =data
});

module.exports = { router };
